﻿using StudentLibrary.Module;
using StudentLibrary.Module.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SQLite;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace StudentLibrary
{
    public partial class FormIssueRefund : Form
    {
        public static int Id { get; set; }
        public FormIssueRefund()
        {
            InitializeComponent();
            LoadContent();
            dataGridViewIssueRefund.Columns[0].ReadOnly = true;
        }

        public void LoadContent()
        {
            try
            {
                string sql = @"SELECT * 
                               FROM IssueRefund";
                dataGridViewIssueRefund.Rows.Clear();
                foreach (DataRow row in sql.SQLQueryAsDataTable().Rows)
                    dataGridViewIssueRefund.Rows.Add(row["id"].ToString(),
                                                     row["idBook"].ToString(),
                                                     row["fio"].ToString(),
                                                     double.Parse(row["dateOfIssue"].ToString()).UnixTimeStampToDateTime().ToString("dd/MM/yyyy"),
                                                     row["dateOfReturn"] == DBNull.Value  || row["dateOfReturn"] == null || string.IsNullOrWhiteSpace(row["dateOfReturn"].ToString())
                                                     ? "" 
                                                     : double.Parse(row["dateOfReturn"].ToString()).UnixTimeStampToDateTime().ToString("dd/MM/yyyy"));
            }
            catch (Exception ex)
            {
                Console.WriteLine("Ошибка: " + ex.Message);
            }
        }

        private void buttonBack_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void buttonAdd_Click(object sender, EventArgs e)
        {
            new FormAddIssueRefund().ShowDialog();
            LoadContent();
        }

        private void buttonEdit_Click(object sender, EventArgs e)
        {
            try
            {
                var row = dataGridViewIssueRefund.SelectedCells[0].OwningRow;

                if (!Book.IsExist(int.Parse(row.Cells[1].Value.ToString())))
                {
                    MessageBox.Show("Книги с таким ИД не существует!", "Внимание", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                var sql = @"UPDATE IssueRefund 
                            SET idBook = @idBook, 
                                fio = @fio, 
                                dateOfIssue = @dateOfIssue, 
                                dateOfReturn = @dateOfReturn 
                            WHERE id = @id";

                DateTime dateOfIssue = DateTime.ParseExact(dataGridViewIssueRefund.SelectedCells[0].OwningRow.Cells[3].Value.ToString(), "dd.MM.yyyy", CultureInfo.InvariantCulture);
                DateTime dateOfReturn = DateTime.ParseExact(dataGridViewIssueRefund.SelectedCells[0].OwningRow.Cells[4].Value.ToString(), "dd.MM.yyyy", CultureInfo.InvariantCulture);
                var isUpdate = sql.SQLNoneQueryWithParametrs(new Dictionary<string, string>()
                {
                    ["@id"] = Id.ToString(),
                    ["@idBook"] = row.Cells[2].Value.ToString(),
                    ["@fio"] = row.Cells[2].Value.ToString(),
                    ["@dateOfIssue"] = (dateOfIssue - new DateTime(1970, 1, 1)).TotalSeconds.ToString(),
                    ["@dateOfReturn"] = (dateOfReturn - new DateTime(1970, 1, 1)).TotalSeconds.ToString()
                });

                if (isUpdate)
                {
                    MessageBox.Show("Запись успешно обновлена!", "Внимание", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    LoadContent();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Ошибка: {ex.Message}");
            }
        }

        private void ForeachRows(string searchText)
        {
            foreach (DataGridViewRow row in dataGridViewIssueRefund.Rows)
            {
                if (!row.IsNewRow)
                {
                    bool rowContainsSearchText = false;

                    foreach (DataGridViewCell cell in row.Cells)
                    {
                        if (cell.Value != null && cell.Value.ToString().IndexOf(searchText, StringComparison.OrdinalIgnoreCase) >= 0)
                        {
                            rowContainsSearchText = true;
                            break;
                        }
                    }

                    row.Visible = rowContainsSearchText;
                }
            }
        }

        private void textBoxSearch_TextChanged(object sender, EventArgs e)
        {
            string searchText = textBoxSearch.Text.Trim();

            if (string.IsNullOrEmpty(searchText))
            {
                foreach (DataGridViewRow row in dataGridViewIssueRefund.Rows)
                {
                    if (!row.IsNewRow)
                    {
                        row.Visible = true;
                    }
                }
            }
            else
            {
                ForeachRows(searchText);
            }
        }

        private void dataGridViewIssueRefund_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && e.ColumnIndex >= 0)
            {
                Id = int.Parse(dataGridViewIssueRefund.Rows[e.RowIndex].Cells[0].Value.ToString());
            }
        }

        private void buttonDelete_Click(object sender, EventArgs e)
        {
            if (Id != 0)
            {
                string sql = $@"DELETE 
                                FROM IssueRefund 
                                WHERE id = {Id}";

                if (sql.SQLNoneQuery())
                {
                    MessageBox.Show("Запись успешно удалена!", "Внимание", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    LoadContent();
                }
            }
        }
    }
}
